using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using NetworkFlowMonitor.Scripts.Data;
using NetworkFlowMonitor.Scripts.Service;
using System.Net;
using System.Diagnostics;

namespace NetworkFlowMonitor.Pages.Devices;

public class DetailsModel : PageModel
{
    private readonly ApplicationDbContext _context;

    public DetailsModel(ApplicationDbContext context)
    {
        _context = context;
    }

    public Device Device { get; set; } = default!;
    public List<TrafficRecord> TrafficRecords { get; set; } = new();

    // 添加连接信息列表
    public List<DeviceConnection> Connections { get; set; } = new();

    public async Task<IActionResult> OnGetAsync(int id)
    {
        var device = await _context.Devices.FirstOrDefaultAsync(m => m.Id == id);
        if (device == null)
        {
            return NotFound();
        }

        Device = device;

        // 获取设备的流量记录
        TrafficRecords = await _context.TrafficRecords
            .Where(t => t.DeviceId == id)
            .OrderByDescending(t => t.Timestamp)
            .Take(50)
            .ToListAsync();

        // 获取设备的连接信息
        Connections = GetDeviceConnections(id);

        return Page();
    }

    // 获取设备连接信息的方法
    private List<DeviceConnection> GetDeviceConnections(int deviceId)
    {
        var connections = new List<DeviceConnection>();

        // 获取设备的IP地址
        var device = _context.Devices.FirstOrDefault(d => d.Id == deviceId);
        if (device == null)
            return connections;

        var deviceIp = device.IpAddress;

        // 从流量监控服务获取当前连接信息
        if (TrafficMonitorService.Instance != null)
        {
            connections = TrafficMonitorService.Instance.GetDeviceConnections(deviceIp);

            // 为每个连接获取URL（反向DNS查找）
            foreach (var connection in connections)
            {
                // 确定远程IP（不是设备IP的那一端）
                var remoteIp = connection.SourceIp == deviceIp ? connection.DestinationIp : connection.SourceIp;
                // connection.Url = ReverseDnsLookup(remoteIp);

                // 格式化数据显示
                connection.SourceIp = $"{connection.SourceIp}";
                connection.DestinationIp = $"{connection.DestinationIp}";

                // 如果是TCP或UDP连接，包含端口信息
                if (connection.ConnectionId.Contains(":"))
                {
                    var parts = connection.ConnectionId.Split(new[] { "->" }, StringSplitOptions.None);
                    if (parts.Length >= 2)
                    {
                        connection.SourceIp = parts[0];
                        connection.DestinationIp = parts[1];
                    }
                }

                // 格式化传输速率和数据量
                // connection.Rate = FormatBytes(connection.BytesTransferred / Math.Max(1, (int)(connection.LastSeen - connection.FirstSeen).TotalSeconds)) + "/s";
                // connection.Download = FormatBytes(connection.BytesTransferred / 2); // 简化处理，假设下载占一半
                // connection.Upload = FormatBytes(connection.BytesTransferred / 2); // 简化处理，假设上传占一半
            }
        }

        return connections;
    }

    // 反向DNS查找，将IP地址转换为域名
    private string ReverseDnsLookup(string ipAddress)
    {
        try
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "nslookup",
                    Arguments = ipAddress,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };

            process.Start();
            var output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();

            // 解析nslookup输出获取域名
            var lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var line in lines)
            {
                if (line.Contains("name = "))
                {
                    var parts = line.Split(new[] { "name = " }, StringSplitOptions.None);
                    if (parts.Length > 1)
                    {
                        return parts[1].TrimEnd('.');
                    }
                }
            }

            return ipAddress; // 如果无法解析，返回原始IP地址
        }
        catch
        {
            return ipAddress; // 出错时返回原始IP地址
        }
    }

    // 格式化字节数
    private string FormatBytes(long bytes)
    {
        string[] units = { "B", "KB", "MB", "GB", "TB" };
        double size = bytes;
        int unitIndex = 0;

        while (size >= 1024 && unitIndex < units.Length - 1)
        {
            size /= 1024;
            unitIndex++;
        }

        return $"{size:0.##} {units[unitIndex]}";
    }
}